package com.weds.edpf.core.service;

import com.weds.core.base.BaseService;
import com.weds.core.resp.JsonResult;
import com.weds.edpf.core.entity.*;
import com.weds.edpf.core.mapper.*;
import com.weds.edpf.core.util.IpUtils;
import com.weds.edpf.core.util.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author zcz
 * @Description 设备定义
 * @Date 2020-06-12
 */
@Service("deviceServiceNew")
public class DeviceService extends BaseService {
	/**
	 * 设备
	 */
	@Resource(name = "deviceMapperNew")
	private DeviceMapper deviceMapper;
	/**
	 * 设备与模块
	 */
	@Resource
	private DevModuleMapper devModuleMapper;
	/**
	 * 增量
	 */
	@Resource
	private JrealNowcmdMapper jrealNowcmdMapper;
	/**
	 * 增量
	 */
	@Resource
	private WtPublicMapper wtPublicMapper;
	/**
	 * 配置文件更新日志
	 */
	@Resource
	private ConfigVerMapper configVerMapper;
	/**
	 *
	 */
	@Resource
	private KqVerMapper kqVerMapper;
	/**
	 * 设备与场所关联
	 */
	@Resource
	private DevMapper devMapper;
	/**
	 * 设备变更记录
	 */
	@Resource
	private LinkDevchangeLogMapper linkDevchangeLogMapper;
	/**
	 * 场所白名单
	 */
	@Resource
	private AcDepUserMapper acDepUserMapper;
	/**
	 * 设备日志
	 */
	@Resource
	private WtDevLogMapper wtDevLogMapper;
	/**
	 * 设备类型
	 */
	@Resource
	private TtDevMapper ttDevMapper;

	@Resource
	private HttpServletRequest request;

	private Logger log = LogManager.getLogger();


	public List<DeviceEntity> selectDeviceDefineList(DeviceEntity record) {
		return deviceMapper.selectDeviceDefineList(record);
	}

	public int deleteByPrimaryKey(String bh) {
		return deviceMapper.deleteByPrimaryKey(bh);
	}

	public int insert(DeviceEntity record) {
		return deviceMapper.insert(record);
	}

	public int insertSelective(DeviceEntity record) {
		return deviceMapper.insertSelective(record);
	}

	public DeviceEntity selectByPrimaryKey(String bh) {
		return deviceMapper.selectByPrimaryKey(bh);
	}

	/**
	 * 设备修改
	 * @param record
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public JsonResult<Object> updateByPrimaryKeySelective(DeviceEntity record) {
		// 查询设备信息
		DeviceEntity device = deviceMapper.selectByPrimaryKey(record.getBh());
		if(Objects.isNull(device)){
			return JsonResult.get("601","未查到设备信息");
		}
		// 查询模块数量
		String gly = UserUtils.currentGly(request);
		String ipAddr = IpUtils.getIpAddr(request);
		// 是否变更模块isChangeModule 1是 0否
		if("1".equals(record.getIsChangeModule())){
			TtDevEntity ttDevEntity = ttDevMapper.selectByPrimaryKey(record.getTtXh());
			if(Objects.nonNull(ttDevEntity)){
				record.setDevLb(Byte.parseByte(ttDevEntity.getDevLb()+""));
				record.setDevType(ttDevEntity.getDevType());
			}
			// 删除设备与模块关联表
			devModuleMapper.deleteByDevSerial(record.getBh());
			// 新增设备与模块关联表
			DevModuleEntity moduleEntity = new DevModuleEntity();
			moduleEntity.setDevSerial(record.getBh());
			moduleEntity.setTtXh(record.getTtXh());
			moduleEntity.setModuleId(record.getModuleId());
			moduleEntity.setSj(new Date());
			moduleEntity.setGlyNo(gly);
			devModuleMapper.insertSelective(moduleEntity);
			// 增量下发
			JrealNowcmdEntity jrealNowcmdEntity = new JrealNowcmdEntity();
			jrealNowcmdEntity.setJdevBh(record.getBh());
			jrealNowcmdEntity.setJtype(7);
			jrealNowcmdEntity.setJoperator(gly);
			jrealNowcmdEntity.setJipAddr(ipAddr);
			jrealNowcmdMapper.insertSelective(jrealNowcmdEntity);
			// 增量下发
			WtPublicEntity wtPublicEntity = new WtPublicEntity();
			wtPublicEntity.setLx(16);
			wtPublicEntity.setLogType(2);
			wtPublicEntity.setIsAll(1);
			wtPublicEntity.setDevSerial(record.getBh());
			wtPublicEntity.setLogSj(new Date());
			wtPublicEntity.setLogIp(ipAddr);
			wtPublicEntity.setGlyNo(gly);
			wtPublicMapper.insertSelective(wtPublicEntity);
		}
		// 修改设备信息
		deviceMapper.updateByPrimaryKeySelective(record);
		Integer dlx = record.getDlx();
		if(2 == dlx){
			// 保存
			ConfigVerEntity configVerEntity = new ConfigVerEntity();
			configVerEntity.setType(0);
			configVerEntity.setLx(3);
			configVerEntity.setLogSj(new Date());
			configVerEntity.setLogIp(ipAddr);
			configVerEntity.setGlyNo(gly);
			// 保存
			configVerMapper.insertSelective(configVerEntity);
			ConfigVerEntity configVerEntity2 = new ConfigVerEntity();
			configVerEntity2.setType(1);
			configVerEntity2.setLx(3);
			configVerEntity2.setLogSj(new Date());
			configVerEntity2.setLogIp(ipAddr);
			configVerEntity2.setGlyNo(gly);
			configVerMapper.insertSelective(configVerEntity2);
		}else if(1 == dlx){
			// 保存
			KqVerEntity kqVerEntity = new KqVerEntity();
			kqVerEntity.setType(0);
			kqVerEntity.setLx(0);
			kqVerEntity.setLogSj(new Date());
			kqVerEntity.setLogIp(ipAddr);
			kqVerEntity.setGlyNo(gly);
			kqVerMapper.insertSelective(kqVerEntity);
			// 保存
			KqVerEntity kqVerEntity1 = new KqVerEntity();
			kqVerEntity1.setType(1);
			kqVerEntity1.setLx(3);
			kqVerEntity1.setLogSj(new Date());
			kqVerEntity1.setLogIp(ipAddr);
			kqVerEntity1.setGlyNo(gly);
			kqVerMapper.insertSelective(kqVerEntity);
		}
		// 查询原始场所
		DevEntity dev = devMapper.selectByDevSerial(record.getBh());
		if(Objects.isNull(dev)){
			dev = new DevEntity();
		}
		// 场所变更
		int devCount = deviceMapper.selectDevCount(record.getBh(), record.getAcdepSerial());
		// 新场所和原场所不一致
		if(0 == devCount){
			// 删除
			devMapper.deleteByDevSerialAndLx("3",record.getBh());
			// 保存场所与设备关联表
			DevEntity devEntity = new DevEntity();
			devEntity.setLx(3);
			devEntity.setDevSerial(record.getBh());
			devEntity.setAcdepSerial(Integer.parseInt(record.getAcdepSerial()));
			devEntity.setModuleId(record.getModuleId());
			devEntity.setSj(new Date());
			devEntity.setGlyNo(gly);
			devMapper.insertSelective(devEntity);
			// 修改消费表的场所字段
			if(6 == record.getDevLb()){
				// 修改消费记录到新场所
				deviceMapper.updateAcdepSerialByDevSerial(record.getAcdepSerial(),record.getBh());
				// 保存场所变更记录表
				LinkDevchangeLogEntity linkDevchangeLogEntity = new LinkDevchangeLogEntity();
				linkDevchangeLogEntity.setDevSerial(record.getBh());
				Long acdepSerial = null == dev.getAcdepSerial() ? null : Long.parseLong(dev.getAcdepSerial()+"");
				linkDevchangeLogEntity.setOldAcdep(acdepSerial);
				linkDevchangeLogEntity.setNewAcdep(Long.parseLong(record.getAcdepSerial()));
				linkDevchangeLogEntity.setSj(new Date());
				linkDevchangeLogEntity.setGlyNo(gly);
				linkDevchangeLogMapper.insertSelective(linkDevchangeLogEntity);
			}
			// 白名单状态 1移动 2合并 0不做处理
			if("1".equals(record.getWhiteStatus())){
				// 刪除新場所在本模塊內的白名單
				System.out.println(record.getAcdepSerial());
				acDepUserMapper.deleteByDepSerialAndModuleId(record.getAcdepSerial(),record.getModuleId());
				// 更新老場所白名單至新場所
				acDepUserMapper.updateByDepSerialAndModuleId(record.getAcdepSerial(),record.getDepName(),dev.getAcdepSerial()+"",dev.getModuleId());
			}else if("2".equals(record.getWhiteStatus())){
				// 旧场所集合
				List<AcDepUserEntity> oldDepUsers = acDepUserMapper.selectByDepSerialAndModuleId(dev.getAcdepSerial()+"",record.getModuleId());
				// 新场所集合
				List<AcDepUserEntity> newDepUsers = acDepUserMapper.selectByDepSerialAndModuleId(record.getAcdepSerial()+"",record.getModuleId());
				// 过滤旧场所有的但是新场所没有的集合
				List<AcDepUserEntity> depUsers = oldDepUsers.stream().filter(m -> !newDepUsers.stream().map(d -> d.getUserSerial()).collect(Collectors.toList()).contains(m.getUserSerial())).collect(Collectors.toList());
				// 删除旧场所
				acDepUserMapper.deleteByDepSerialAndModuleId(dev.getAcdepSerial()+"",record.getModuleId());
				// 新增新场所
				for (AcDepUserEntity depUser:depUsers){
					depUser.setDepSerial(Integer.parseInt(record.getAcdepSerial()));
					depUser.setGlyNo(gly);
					depUser.setSj(new Date());
					depUser.setDepLname(record.getDepName());
					acDepUserMapper.insertSelective(depUser);
				}
			}
		}
		// 下发增量日志
		WtPublicEntity wtPublicEntity = new WtPublicEntity();
		wtPublicEntity.setLx(16);
		wtPublicEntity.setLogType(1);
		wtPublicEntity.setIsAll(1);
		wtPublicEntity.setDevSerial(record.getBh());
		wtPublicEntity.setLogSj(new Date());
		wtPublicEntity.setLogIp(ipAddr);
		wtPublicEntity.setGlyNo(gly);
		wtPublicMapper.insertSelective(wtPublicEntity);
		// 保存操作日志
		WtDevLogEntity devLogEntity = new WtDevLogEntity();
		devLogEntity.setLx(1);
		devLogEntity.setLogType(1);
		devLogEntity.setLogState(0);
		devLogEntity.setLogSj(new Date());
		devLogEntity.setLogIp(ipAddr);
		devLogEntity.setGlyNo(gly);
		devLogEntity.setLogBz("修改设备：设备编号："+record.getBh());
		devLogEntity.setModuleId(record.getModuleId());
		wtDevLogMapper.insertSelective(devLogEntity);
		return succMsg();
	}

	public int updateByPrimaryKey(DeviceEntity record) {
		return deviceMapper.updateByPrimaryKey(record);
	}

	public List<DeviceEntity> selectListByEntity(DeviceEntity record) {
		return deviceMapper.selectListByEntity(record);
	}

	/**
	 * 批量删除
	 * @param devSerials
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
    public JsonResult<Object> deleteBatch(String devSerials) {
		// 登录账号
		String gly = UserUtils.currentGly(request);
		// 真实ip
		String ipAddr = IpUtils.getIpAddr(request);
		String[] split = StringUtils.split(devSerials, ",");
		for (String devSerial:split){
			DeviceEntity deviceEntity = deviceMapper.selectByPrimaryKey(devSerial);
			// 验证编号是否真实存在
			if(Objects.isNull(deviceEntity)){
				return JsonResult.get("601","未查到设备信息");
			}
			// 调用删除存储过程
			deviceMapper.callDevDelete(devSerial);
			JrealNowcmdEntity jrealNowcmdEntity = new JrealNowcmdEntity();
			jrealNowcmdEntity.setJdevId(Integer.parseInt(deviceEntity.getBh()));
			jrealNowcmdEntity.setJtype(8);
			jrealNowcmdEntity.setJoperator(gly);
			jrealNowcmdEntity.setJoperator(gly);
			jrealNowcmdEntity.setJipAddr(ipAddr);
			// 保存增量日志
			jrealNowcmdMapper.insertSelective(jrealNowcmdEntity);
			// 修改设备类型为99  逻辑删除
			deviceMapper.updateDevLbByBh("99",devSerial);
			// 添加日志
			WtDevLogEntity devLogEntity = new WtDevLogEntity();
			devLogEntity.setLx(2);
			devLogEntity.setLogType(1);
			devLogEntity.setLogState(0);
			devLogEntity.setLogSj(new Date());
			devLogEntity.setLogIp(ipAddr);
			devLogEntity.setGlyNo(gly);
			devLogEntity.setModuleId(deviceEntity.getModuleId());
			devLogEntity.setLogBz("删除设备：设备编号："+deviceEntity.getBh());
			wtDevLogMapper.insertSelective(devLogEntity);
		}
		return succMsg();
    }
    
    	public int insertBatch(List<DeviceEntity> list) {
		return deviceMapper.insertBatch(list);
	}

	/**
	 * 根据设备编号查询场所信息
	 * @param devSerial
	 * @return
	 */
	public Map<String,String> selectDepByDevSerial(String devSerial){
		return deviceMapper.selectDepByDevSerial(devSerial);
	}
	/**
	 * 根据设备编号查询模块信息
	 * @param devSerial
	 * @return
	 */
	public Map<String,String> selectModuleByDevSerial(String devSerial){
		return deviceMapper.selectModuleByDevSerial(devSerial);
	}
}
